package com.lqg.bookLibrary.service.webService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lqg.bookLibrary.common.core.redis.RedisCache;
import com.lqg.bookLibrary.common.exception.ServiceException;
import com.lqg.bookLibrary.pojo.Users;
import com.lqg.bookLibrary.service.IUsersService;
import com.lqg.bookLibrary.service.impl.MailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class RegisterService {
    @Autowired
    private MailServiceImpl mailService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IUsersService userService;

    //获取验证码
    public String getCheckCode(String email){
        String msg = null;
        QueryWrapper<Object> wrapper = new QueryWrapper<>();
        QueryWrapper<Object> eq = wrapper.eq("email", email);
        Boolean b = userService.lambdaQuery().eq(Users::getEmail,email).exists();
        if(b){
            msg = "该邮箱已经存在";
        }else {
            String checkCode = mailService.sendCheckCode(email);
            String coedKey = email+checkCode;  //key的规则
            boolean flag = false;
            try {
                redisCache.setCacheObject(coedKey,checkCode);
                flag = redisCache.expire(coedKey,180L);  //设置存储时间
            } catch (Exception e) {
                e.printStackTrace();
            }
            if(flag){
                msg = "验证码发送成功";
            }else {
                msg = "redis异常";
                throw new ServiceException(msg);
            }
        }
        return msg;
    }

    //验证验证码
    public String verifyCheckCode(String neckName,String email,String password,String checkCode){
        String msg = null;
        String coedKey = email+checkCode;  //key的规则
        String rightCode = null;
        try {
            rightCode = redisCache.getCacheObject(coedKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(rightCode == null){
            msg = "验证码已经过时";
            return msg;
        }
        if(checkCode.equals(rightCode)){
            if(userService.save(
                    new Users())
            ){
                msg = "验证码正确";
            }else {
                msg = "数据库异常";
                throw new ServiceException(msg);
            }
        }else {
            msg = "验证码错误";
        }
        return msg;
    }
}
